package info.motteke.net;

import java.util.*;
import java.util.Map.Entry;

public class UrlBuilder {

    private final Map<String, List<String>> params;

    public UrlBuilder(){
        this.params = new HashMap<String, List<String>>();
    }

    public UrlBuilder param(String key, String value){
        List<String> list = this.params.get(key);

        if(list == null){
            list = new ArrayList<String>();
            this.params.put(key, list);
        }
        list.add(value);

        return this;
    }

    public String build(String base){
        if(this.params.size() == 0){
            return base;
        }

        StringBuilder buf = new StringBuilder();

        for(Entry<String, List<String>> entry : this.params.entrySet()){
            String key = entry.getKey();
            for(String value : entry.getValue()){
                buf.append(key);
                buf.append("=");
                buf.append(value);
                buf.append("&");
            }
        }
        buf.deleteCharAt(buf.length() - 1);
        char delim = base.indexOf('?') == -1 ? '?' : '&';
        return new StringBuilder().append(base)
                                  .append(delim)
                                  .append(buf)
                                  .toString();
    }
}
